<script setup lang="ts">
import { List, ListItem, Button, Space } from "ant-design-vue";
import {
  HomeOutlined,
  PlusOutlined,
  StarOutlined,
} from "@ant-design/icons-vue";
import { Service, PlaylistOutput } from "../api";
import { ref, watch, h } from "vue";
import CreatePlaylistModal from "./CreatePlaylistModal.vue";
import { useStore } from "../stores/";
const store = useStore();
const dataSource = ref<PlaylistOutput[]>([]);
const loadData = async () => {
  try {
    dataSource.value = await Service.getAllPlaylist();
  } catch (error) {
    console.log(error);
  }
};

const selectPlaylist = (reocrd: PlaylistOutput | undefined) => {
  store.setCurPlaylist(reocrd);
};

const createPlaylistModalOpen = ref(false);

watch(
  () => store.userInfo,
  () => {
    if (store.userInfo) {
      loadData();
    } else {
      dataSource.value = [];
    }
  },
  {
    immediate: true,
  }
);

defineExpose({
  loadData,
});
</script>
<template>
  <Space direction="vertical" style="width: 100%; margin-top: 10px">
    <div class="title">Music</div>
    <Button
      type="text"
      style="width: 100%; margin-top: 10px; text-align: left"
      :icon="h(HomeOutlined)"
      :class="store.curPlaylist == undefined ? 'active' : ''"
      @click="selectPlaylist(undefined)"
      >音乐库</Button
    >
    <div class="title">我的歌单</div>
    <div v-if="store.userInfo != undefined">
      <!-- <div class="add">+ </div> -->
      <Button
        type="dashed"
        style="
          width: 100%;
          background-color: rgb(232, 232, 232);
          text-align: left;
        "
        :icon="h(PlusOutlined)"
        @click="createPlaylistModalOpen = true"
        >创建歌单</Button
      >
    </div>
    <template v-if="dataSource.length > 0">
      <List :data-source="dataSource" size="small">
        <template #renderItem="{ item }: { item: PlaylistOutput }">
          <ListItem
            @click="selectPlaylist(item)"
            class="item"
            :class="store.curPlaylist?.id == item.id ? 'active' : ''"
          >
            <StarOutlined />
            {{ item.title }}
          </ListItem>
        </template>
      </List>
    </template>
    <div v-else class="error">
      <span v-if="store.userInfo == undefined"> 登录后显示歌单</span>
      <span v-else>当前没有任何歌单</span>
    </div>
  </Space>
  <CreatePlaylistModal
    v-model:open="createPlaylistModalOpen"
    @finish="loadData"
  ></CreatePlaylistModal>
</template>
<style scoped>
.title {
  font-size: 14px;
  font-weight: 800;
  color: #666;
  margin-left: 10px;
  margin-top: 10px;
  /* text-align: center; */
}
.error {
  height: 32px;
  line-height: 32px;
  color: #600;
  margin-left: 10px;
}
.item {
  cursor: pointer;
  border-radius: 8px;
}
.item:hover {
  background-color: rgba(0, 0, 0, 0.06);
}
.active {
  background-color: rgba(0, 0, 0, 0.06);
}
</style>
